using Baula.TextGen.ActiveTemplating.Tokenizer.Tokens;

namespace Baula.TextGen.ActiveTemplating.Tokenizer.TokenParsers
{
    internal class BlockExpressionParser : ExpressionParserBase
    {
        private bool _hasEnded;

        public static bool CanStartToken(string text)
        {
            return text == "{{";
        }

        public override bool CanAppend(char c)
        {
            return !_hasEnded;
            if (_hasEnded)
                return false;

            if (StringBuilder.ToString().StartsWith("{{"))
                return true;

            return c == '{';
        }

        public override void Append(char c)
        {
            if (_hasEnded)
                throw new CannotAppendToClosedTokenException(0);

            StringBuilder.Append(c);
            if (c == '\"')
                IsInString = !IsInString;

            _hasEnded = StringBuilder.ToString().EndsWith("}}");
        }

        public override IToken CreateToken()
        {
            if (IsInString)
                throw new MissingEndOfStringExpressionException(0);
            
            var asString = StringBuilder.ToString();
            if (!_hasEnded)
                throw new MissingEndOfBlockExpressionException(0);
            
            return new BlockExpressionToken(asString.CutFromEnd(2));
        }
    }
}